package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrdersettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrdersettingService.class)
@Transactional
public class OrdersettingServiceImpl implements OrdersettingService {
@Autowired
private OrdersettingDao ordersettingDao;

    //前端上传预约信息的文件，保存到数据库中
    public void add(List<OrderSetting> list) {
        if(list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                //得到上传文件的时间
                Date orderDate = orderSetting.getOrderDate();
                //调用dao层的根据日期判断有没有上传过文件的方法，判断这天有没有上传过文件，
                long countByDate = ordersettingDao.findCountByDate(orderDate);
                if(countByDate > 0){
                    //如果返回值大于0则上传过文件，执行修改方法
                    ordersettingDao.editNumberDate(orderSetting);
                }else {
                    //如果这天没有上传过文件，则执行添加方法
                    ordersettingDao.add(orderSetting);
                }
            }
        }
    }

    //在页面显示出预约人数与以约人数的关系
    //前端传过来的时间格式为2020-9
    public List<Map> getOrdersettingByMonth(String date) { //2020-9
        //-1日期格式变成2020-9-1
        String between = date + "-1";
        //-日期格式变成2020-9-31
        String end = date + "-31";
        //根据日期查询出预约信息
        Map<String , String> m = new HashMap<String, String>();
        m.put("between" , between);
        m.put("end" , end);
        //调用dao层的方法，得到根据日期查询出来的预约信息
        List<OrderSetting> list = ordersettingDao.getOrdersettingByMonth(m);
        //前端所接受的格式为：data：1 ，number: 120, reservations: 1
        //设置一个list集合，类型为map，后面用来包装好数据然后返回到前端
        List<Map> result = new ArrayList<Map>();
        //遍历从dao层得到的数据集合，然后将他们打包成前端所需要的格式
        if(list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                int orderDate = orderSetting.getOrderDate().getDate();
                int number = orderSetting.getNumber();
                int reservations = orderSetting.getReservations();
                //设置一个map集合，包装数据
                Map<String , Object> map = new HashMap<String, Object>();
                map.put("date" , orderDate);
                map.put("number" , number);
                map.put("reservations" , reservations);
                //将map集合添加到前面设置的list集合中
                result.add(map);
            }
        }
        return result;
    }

    //设置预约人数
    public void setNumberByDate(OrderSetting orderSetting) {
        ordersettingDao.setNumberByDate(orderSetting);
    }
}
